/**
 * @description: 将base64文件转换为blob
 * @param {string} base64
 */
export const dataBase64toBlob = (base64: string) => {
  const arr = base64.split(',');
  const mime = arr[0]?.match(/:(.*?);/)?.[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  // eslint-disable-next-line no-plusplus
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
};

/**
 * @description: 通过URL下载文件
 * @param {string} url 下载地址
 * @param {*} name 下载文件名称
 */
export const downloadFileByUrl = (url: string, name = `${Date.now()}`) => {
  const a = document.createElement('a');
  a.setAttribute('href', url);
  a.setAttribute('download', name);
  a.setAttribute('target', '_blank');
  const clickEvent = document.createEvent('MouseEvents');
  clickEvent.initEvent('click', true, true);
  a.dispatchEvent(clickEvent);
};

/**
 * @description: 通过Base64下载文件
 */
export const downloadFileByBase64 = (base64: string, name = `${Date.now()}`) => {
  const myBlob = dataBase64toBlob(base64);
  const myUrl = URL.createObjectURL(myBlob);
  downloadFileByUrl(myUrl, name);
};

/**
 * @description: 加载图片
 * @param {string} src 图片地址
 */
export const loadImage = (src: string) => new Promise((resolve, reject) => {
  const img = new Image();
  img.src = src;
  img.onload = () => {
    resolve(img);
  };
  img.onerror = () => {
    reject(new Error('图片加载失败'));
  };
});
